#coding:utf8
from config import *
from routin import *
from gui import *
from gui2 import *
from mpp import *

def on_move(x,y):
    if (cfg.enter_pressed or cfg.x2_pressed) and not cfg.is_suo:
        cfg.enter_pressed_then_other = True
        cfg.x2_pressed_then_other = True
        cfg.is_suo = True
        cfg.suo_dis = max(1, cal_dis(get_cur_pos() , cfg.fix_pos))
        cfg.suo_to = cfg.to

    if (cfg.enter_pressed or cfg.x2_pressed ) and cfg.is_suo:
        cfg.enter_pressed_then_other = True
        cfg.x2_pressed_then_other = True
        if cfg.x2_pressed and not cfg.w2showing:
            clear(True)
            cfg.show_one_on = True
            cfg.force_show = True

        d =  cal_dis(get_cur_pos(),cfg.fix_pos)- cfg.suo_dis
        to_lock.acquire()
        cfg.has_pos_vert = True
        if d >= 0:
            cfg.to = cut_to(cfg.suo_to + d * get_suo_di())            
        else:
            cfg.to = cfg.suo_to * cal_dis(get_cur_pos(),cfg.fix_pos) / cfg.suo_dis
        
        set_to_change_time()
        to_lock.release()
        
    cfg.last_move_time = time.time()
    
    if float(cfg.sum) != 0:
        x, y = getp(cfg.last_mouse_pos, False)
        sx, sy = cfg.fix_pos
        dx = x - sx
        dy = y - sy
        
        dx = round(dx*float(cfg.sum) + dx)
        dy = round(dy*float(cfg.sum) + dy)
        
        cfg.move_task = (sx + dx - cfg.last_mouse_pos[0], sy + dy - cfg.last_mouse_pos[1], 1)
        print('move_task', cfg.move_task)
        cfg.isShow = False
        clear(False)
        
    if cfg.x2_mode and not cfg.x2_pressed:
        cfg.x2_mode = False
        x, y = get_cur_pos()
        cfg.move_task = (cfg.x2_mode_dst[0] - x,cfg.x2_mode_dst[1] - y, 2)
        print('move_task', cfg.move_task)
        cfg.isShow = False
        clear(False)    
        
def moveF():    
    while True:
        time.sleep(0.01)                    
        if time.time() - cfg.set_fix_time < 0.02:
            if get_cur_pos() != cfg.fix_pos:
                print('diff', time.time() - cfg.set_fix_time, get_cur_pos(), cfg.fix_pos)
                cfg.fix_pos = get_cur_pos()
            
        if time.time() - cfg.click_time > 0.2 and cfg.click_time >= 0:
            cfg.click_time = -1
            mouse.Controller().click(mouse.Button.left)
            
            
        if cfg.move_task != None:
            dx, dy , ty= cfg.move_task
            d = move_task_delay1
            if ty == 2:
                d = move_task_delay2            
            if time.time() - cfg.last_move_time > d:            
                cfg.move_task = None
                x, y = get_cur_pos()
                cfg.fix_pos = (x + dx, y + dy)
                cfg.set_fix_time = time.time()
                try:
                    mouse.Controller().move(dx, dy)
                    deal_reset_one()
                except Exception as e:
                    print(e)            
def get_snap_sort():
    a = copy.deepcopy(cfg.w2snap)
    if len(a) == 0:
        return []
    
    a = sorted(a,key=lambda x: int(x[0]))                        
    max_idx = 0
    for i in range(len(a)):
        if is_in_screen(a[i][1], a[i][2]):
            max_idx = i
    print('max_idx', max_idx)
    return a[0:max_idx+1]
def ctrl2():
    a = get_snap_sort()
    if len(a) > 0:
        mouse.Controller().position = (a[-1][1], a[-1][2])
        clear(True)
        
def on_click2(x, y, button, pressed,deal_x):
    print('click',x,y, button,pressed, deal_x)
    if cfg.x2_mode and 'x1' not  in str(button) and 'x2' not  in str(button):
        cfg.x2_mode = False
        
    if (False or deal_x) and ('x1' in str(button) or 'x2' in str(button)):
        if pressed:            
            if not cfg.x2_pressed:
                cfg.x2_pressed = True
                cfg.x2_pressed_then_other = False
            else:
                cfg.x2_pressed_then_other = True
                cfg.showCut = not cfg.showCut
        if not pressed:
            cfg.x2_pressed =False
            if not cfg.x2_pressed_then_other:
                if 'x1' in str(button):
                    if cfg.x2_mode:
                        cfg.x2_mode = False
                        mouse.Controller().position = (cfg.x2_mode_dst[0],cfg.x2_mode_dst[1])
                        clear(True)                        
                    else:
                        xing()                        
                        deal_xing_q()
                                                    
                    
                if 'x2' in str(button):
                    if cfg.sum != '0':
                        deal_manu_scroll()  
                    elif cfg.w2showing and not cfg.x2_mode:
                        a = get_snap_sort()
                        
                        if len(a) == 0:
                            return
                        
                        if len(a) == 1:
                            mouse.Controller().position = (a[0][1],a[0][2] )
                            clear(True)
                            return
                        cfg.snap = a
                        cfg.x2_mode = True
                        cfg.x2_mode_d = 100
                        x2_d_to_dst()
                    elif cfg.x2_mode:
                        if cfg.x2_mode_d == 0:
                            cfg.x2_mode_d = 100
                        else:
                            cfg.x2_mode_d -= 50
                            if cfg.x2_mode_d < 0:
                                cfg.x2_mode_d = 0
                        x2_d_to_dst()
                                                
                    else:
                        deal_add()
            else:
                cfg.is_suo =False
        return
    
    if ('x1' in str(button) or 'x2' in str(button)):
        return
    
    if cfg.mouse_pressed and pressed:
        return
    
    if pressed:
        cfg.mouse_pressed = True
    else:
        cfg.mouse_pressed = False
        
    if cfg.isOn2:
        cfg.isShow = True
    else:
        cfg.isShow = False
    if cfg.always_show_one:      
        cfg.show_one_on = True
    else:
        cfg.show_one_on = False
    ori = cfg.force_show
    clear(True)
    if pressed:
        cfg.force_show = ori
        
def on_click(x, y, button, pressed):
    on_click2(x, y, button, pressed,False)

def deal_chu():
    if cfg.sum != '0':
        cfg.sum = '0'
        return
    update_du(True)

    
def on_press2(key):   
    a = decode(key, False)           
    if a >= 0 and a <= 10:
        if a == 10 and cfg.sum[-1] == '.':
            cfg.sum = cfg.sum[:-1]
            if len(cfg.sum) == 1:
                a = int(cfg.sum)
                if a >= 1 and a <= 9:
                    deal_enter_pressed('', a)
                    return                
            dotdot()
            return
            
        if a == 0 and cfg.sum == '0':
            if is_sca():
                if get_cur_pos() == cfg.sca_cur_pos:
                    mouse.Controller().position = getp()
                    clear_sca()
                    return 
                update_du(False)
                return 
            clear(True)
            return 
        
        cfg.sum = deal_sum(cfg.sum, a, sum_max_l)
        print('update sum', cfg.sum)
        
    if a == 14:
        deal_chu()
        
    if a == 16:
        cfg.lock = not cfg.lock
        cfg.lock_xing_mode = False
        cfg.lock_jia_mode = False
        cfg.lock_xing_last_move = (0, 0)
        if cfg.sum != '0' and cfg.lock:
            re = cfg.sum
            cfg.sum = '0'
            replay(re)
            cfg.lock = False

    if a == 12: # -
        if cfg.sum != '0':
            deal_e()
            cfg.click_time = time.time()
            return
        mouse.Controller().click(mouse.Button.left)            
            
    if a == 13: #*
        xing()            
        deal_xing_q()
        
    if a == 11: # +
        deal_add()
        
def set_key_sign(key, a):    
    st = str(key)
    if 'ctrl' in st and not   cfg.ctrl_pressed:
        cfg.ctrl_pressed = True

    if 'alt' in st and not cfg.alt_pressed:
        cfg.alt_pressed = True
    if 'pause' in st:
        if not cfg.pause_pressed:
            cfg.pause_pressed = True
            cfg.pause_pressed_then_other = False
        else:
            cfg.pause_pressed_then_other = True
    if a == 15:
        if not cfg.enter_pressed:
            cfg.enter_pressed = True
            cfg.enter_pressed_then_other = False
        else:
            cfg.enter_pressed_then_other = True
           
def deal_ctrl_pressed(st, a):    
    if a >= 0 and a <= 10:
        cfg.sum = '0'
        deal_lock(a)
        if cfg.alt_pressed:
            cfg.lock = True
        return
    if a == 15:
        cfg.cmd_mode = True
        
def deal_pause_pressed(st, a):    
    if 'caps_lock' in st:
        cfg.pause_move = get_cur_pos()
        return
    if a == 15:
        cfg.move_to_win = True
        return
    
    if a == 14:
        x, y = get_cur_pos()
        idx = get_screen_indx(x, y)
        idx += 1
        if idx > 1:
            idx = 0
        aa,b,c,d =  screen_config_for_indx[idx]
        
        mouse.Controller().position = ((aa+c) //2, (b+d) //2)
        
        return
    if (a >= 0 and a <= 10):
        x, y = get_cur_pos()
        idx = get_screen_indx(x, y)
        aa,b,c,d =  screen_config_for_indx[idx]
        dx = round((aa + c) / 10 * a)
        g = 0
        if a == 10:
            g = 5        
        mouse.Controller().position = dx - g, y
        return
    
    if ((a >= 0 and a <= 10) or a in (13, 14, 16)):
        if a == 16:
            a = 10
        if a == 14:
            a = 2
        if a == 13:
            a = 6
        deal_lock(a)
        return
    if a == 12:
        mouse.Controller().click(mouse.Button.right, 1)
        return
    if a == 11:
        mouse.Controller().click(mouse.Button.middle, 1)
        return
    

def deal_cmd(st, a):    
    if a < 0:
        return False
    if a == 11:
        cfg.isOn2 = not cfg.isOn2
        return False
    
    if a == 12:
        cfg.reset_show_one = not cfg.reset_show_one
        return False
    
    if a == 13:
        cfg.show_mouse_tip = not cfg.show_mouse_tip
        return False
    
    if a == 14:    
        cfg.left_mouse = []
        cfg.right_mouse = []
        print('clear mouse')
        return False
    
    if a == 16:
        cfg.set_mode = True
        return False
    
    if a >= 0 and a <= 10:
        move_p(a)
        return False
    
    return False

def deal_enter_pressed(st, a):
    if a == 0:
        cfg.isShow = False
        clear(True)
        return
        
    if a == 11:
        cfg.always_show_one = not cfg.always_show_one
        return
       
    if a == 10:
        cfg.show_mouse_tip = not cfg.show_mouse_tip
        return
    
    if a == 13:
        cfg.show_mouse_tip2 = not cfg.show_mouse_tip2
        return
    
    use_pos = False
    if cfg.sum != '0':
        deal_e(False)
        use_pos = True        
        
    if a == 5:
        cfg.cmd_mode = True
        return
    
    if a not in arrm:
        return
    dx, dy = arrm[a]    
    dx = -dx * enter_gap
    dy = -dy * enter_gap
    print('enter', st, a)
    clear(False, False)
    if use_pos:
        p = cfg.fix_pos
    else:
        p = get_cur_pos()
    cfg.fix_pos = (p[0] + dx, p[1] + dy)
    cfg.show_one_onetime = True
    
def deal_lock_outer(a):
    if a == 11:
        cfg.lock_jia_mode = not cfg.lock_jia_mode
        cfg.lock_xing_mode = False
        return True
    
    if a == 13:
        cfg.lock_xing_mode = not cfg.lock_xing_mode
        cfg.lock_jia_mode = False
        return True
    
    if a == 14:
        deal_chu()
        return True
    
    if not cfg.lock_xing_mode and not cfg.lock_jia_mode:
        if  a >= 0 and a <= 10:
            deal_lock(a)
            return True
        return False
    
    if cfg.lock_xing_mode:        
        if a >= 0 and a <= 10:
            cfg.sum = deal_sum(cfg.sum, a, sum_max_l)
            return True
        
        if a == 15:
            cfg.enter_pressed_then_other = True
            if '0.' in cfg.sum:
                a = -int( cfg.sum.replace('0.', ''))
            elif '.' in  cfg.sum:
                a = 0                    
            else:
                a = int(cfg.sum)
            cfg.sum = '0'
            mouse.Controller().move(a*cfg.lock_xing_last_move[0], a*cfg.lock_xing_last_move[1])
            return True
        return False
    
    if cfg.lock_jia_mode:
        if a in (0, 10):
            cfg.sum = deal_sum(cfg.sum, a, sum_max_l)
            return True
        
        if a >= 1 and a <= 9:
            if cfg.sum == '0':
                mouse.Controller().move(a*cfg.lock_xing_last_move[0], a*cfg.lock_xing_last_move[1])
                
            elif '0.' in cfg.sum:
                cfg.sum = '0'
                mouse.Controller().move(-a*cfg.lock_xing_last_move[0], -a*cfg.lock_xing_last_move[1])
                
            cfg.sum = '0'            
            return True
        
        return False
    return False                
        
def on_press(key):
    cfg.key_input_time = time.time()
    st = str(key)
    a = decode(key, True)                  
            
    if cfg.x2_mode and a != 15 and a != -2:
        cfg.x2_mode = False
    #print('press', st, a, time.time())
    if a == -2:
        return
    set_key_sign(key, a)
    
    if cfg.cmd_mode:
        cfg.enter_pressed_then_other = True
        cfg.cmd_mode = deal_cmd(st, a)
        print('cmd', cfg.cmd_mode)
        return
    
    if cfg.set_mode:
        cfg.set_mode = deal_set(st, a)
        cfg.enter_pressed_then_other = True
        print('set', cfg.set_mode)
        return
    
    if cfg.ctrl_pressed:
        deal_ctrl_pressed(st, a)
        cfg.enter_pressed_then_other = True
        return
    
    if cfg.pause_pressed and 'pause' not in st:
        deal_pause_pressed(st, a)
        cfg.pause_pressed_then_other = True
        cfg.enter_pressed_then_other = True
        return
    
    if cfg.enter_pressed and a != 15:
        cfg.enter_pressed_then_other = True
        deal_enter_pressed(st, a)
        return
    
    if 'scroll' in st:
        mouse.Controller().click(mouse.Button.left, 2)
        
    if 'caps_lock' in st:
        deal_pressed()
                               
    if cfg.lock :
        r = deal_lock_outer(a)
        if r:
            return

    on_press2(key)
    cfg.last_mouse_pos = get_cur_pos()

def on_release(key):
    cfg.key_input_time = time.time()
    st = str(key)
    a = decode(key, False)
    print('release', st, a, time.time())
    if a ==15 :
        cfg.enter_pressed = False
        cfg.is_suo = False
        if cfg.enter_pressed_then_other:
            return
        
        if cfg.lock:
            cfg.cmd_mode = True
            return        
        deal_e()
        
    if 'pause' in st :
        cfg.pause_pressed = False
        if cfg.pause_pressed_then_other:
            return

        if  time.time() - cfg.pause_press_time  < 1:
            cfg.pause_key = not cfg.pause_key
            cfg.pause_press_time = 0
            return
        
        cfg.pause_press_time = time.time()            
        
    if 'ctrl_l' in st:
        if time.time() - cfg.ctrl_l_time < 0.2:
            ctrl2()
        cfg.ctrl_l_time = time.time()
        
    if 'ctrl' in st :
        cfg.ctrl_pressed = False
        cfg.is_suo = False

    if 'alt' in st :
        cfg.alt_pressed = False
        
def pro_get(q):
    while True:
        aa = q.get()
        ty, a, x, y, t = aa
        if ty=='t1up':
            on_click2(0,0,'x1',False,True)
            continue
        if ty=='t1down':
            on_click2(0,0,'x1',True,True)
            continue
        if ty=='t2up':
            on_click2(0,0,'x2',False,True)
            continue
        if ty=='t2down':
            on_click2(0,0,'x2',True,True)
            continue

        if ty == 'w':
            if str(a) == 'None':
                continue
            if not cfg.w2showing:
                continue
            if cfg.force_scroll:
                continue
            if cfg.enter_pressed:
                cfg.enter_pressed_then_other = True
                continue
            if cfg.x2_pressed:
                cfg.x2_pressed_then_other = True
                continue
            if cfg.x2_mode:
                if x > 0:                    
                    for i in range(len(cfg.snap)):
                        d =i * 100 / (len(cfg.snap) - 1)  
                        if  d> cfg.x2_mode_d:
                            cfg.x2_mode_d =  d
                            break
                else:
                    for i in range(len(cfg.snap)):
                        d = (len(cfg.snap) - 1- i) * 100 / (len(cfg.snap) - 1)
                        if  d < cfg.x2_mode_d:
                            cfg.x2_mode_d = d
                            break
                x2_d_to_dst()
                continue
            to_lock.acquire()
            dom = -2
            if cfg.has_invert:
                cfg.has_invert = False
                if x > 0:
                    dom = 1
                else:
                    dom = -1
            else:
                if x > 0:
                    cfg.to = cut_to(cfg.to+get_scroll_sca())                    
                else:
                    cfg.to = cut_to(cfg.to-get_scroll_sca())                    
            
            cfg.has_pos_vert = True
            set_to_change_time()
            to_lock.release()
            if dom != -2:
                deal_manu_scroll(dom)
            continue
        
        aa = (a, x, y, t)
        if cfg.x2_mode:
            if cfg.x2_pressed:
                cfg.x2_pressed_then_other = True
                deal_x2_move(x, y)
        deal_mouse_mode(a, x, y)
        gq.put(aa)
        do_mouse_jump(a)                       
       
        
if __name__ == '__main__':    
    def win32_event_filter(msg, data):
        if cfg.enter_pressed or cfg.x2_pressed:
            return
        if (str(msg)=='522' and  cfg.w2showing and not cfg.isShow ):
            print(msg,data)
            lis.suppress_event()
            
    lis = mouse.Listener(win32_event_filter=win32_event_filter)
    lis.start()

    jumpT = threading.Thread(target=jump_bg)
    jumpT.daemon = True
    jumpT.start()
    thrb = threading.Thread(target=thrf)
    thrb.daemon = True
    thrb.start()
    
    mouse_listener = mouse.Listener(on_move=on_move,on_click=on_click)
    mouse_listener.start()        
    moveT = threading.Thread(target=moveF)
    moveT.daemon = True
    moveT.start()
    load_pos()
    listener = keyboard.Listener(
        on_release=on_release,
        on_press=on_press,
    )
    
    listener.start()        
    app = QApplication([])   
    w2 = my77()
    w3 = my3()
    w4 = my4()
    q = mp.Queue()    
    p = mp.Process(target=foo, args=(q,))
    p.daemon = True
    p.start()
    print('pid', os.getpid(), p.pid)        
            
    tt = threading.Thread(target=pro_get,args=(q,))
    tt.daemon = True
    tt.start()
        
    app.exec_()        